package com.cet.algorithm.二叉树.翻转二叉树;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @program: algorithm
 * @description: 二叉树翻转
 * @author: 陈恩涛
 * @create: 2022-07-18 16:52
 **/
public class LC226 {

    public static void main(String[] args) {

    }

    /**
     * 递归法
     * @param root 二叉树节点
     * @return 结果
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        swapChildren(root);
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    private void swapChildren(TreeNode node) {
        final TreeNode temp = node.left;
        node.left = node.right;
        node.right = temp;
    }

    /**
     * bfs层级遍历
     * @param root 二叉树根节点
     * @return 结果
     */
    public TreeNode invertTree2(TreeNode root) {
        if (root == null) {
            return null;
        }
        final Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            while (len > 0) {
                final TreeNode cur = queue.poll();
                if (cur.left != null || cur.right != null) {
                    swapChildren(cur);
                    if (cur.left != null) {
                        queue.offer(cur.left);
                    }
                    if (cur.right != null) {
                        queue.offer(cur.right);
                    }
                }
                len--;
            }
        }
        return root;
    }

    /**
     * 二叉树通用遍历法
     * @param root 二叉树根节点
     * @return 结果
     */
    public TreeNode invertTree3(TreeNode root) {
        if (root == null) {
            return null;
        }
        final Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            if (cur != null) {
                stack.pop();
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.left != null) {
                    stack.push(cur.left);
                }
                stack.push(cur);
                stack.push(null);
            } else {
                // Null节点出栈
                stack.pop();
                cur = stack.pop();
                swapChildren(cur);
            }
        }
        return root;
    }
}
